<template>
  <div class="editor-container">
    <div class="editor-header">
      <el-input v-model="page.title" placeholder="页面标题" style="width: 200px" />
      <div class="actions">
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button @click="handlePreview">预览</el-button>
      </div>
    </div>
    
    <el-container class="editor-main">
      <el-aside width="200px" class="components-panel">
        <div class="panel-title">组件库</div>
        <div
          v-for="(component, key) in components"
          :key="key"
          class="component-item"
          draggable="true"
          @dragstart="handleDragStart($event, key)"
        >
          <el-icon><component :is="component.icon" /></el-icon>
          <span>{{ component.label }}</span>
        </div>
      </el-aside>
      
      <el-main class="canvas-container">
        <div 
          class="canvas"
          @dragover.prevent
          @drop="handleDrop($event)"
          @click="handleCanvasClick"
        >
          <div
            v-for="(item, index) in page.config.components"
            :key="index"
            class="component-wrapper"
            :class="{ active: selectedIndex === index }"
            @click.stop="handleSelectComponent(index)"
          >
            <component
              :is="item.type === 'el-text' ? 'div' : item.type"
              v-bind="item.props"
              :style="{
                color: item.props.color,
                fontSize: item.props.fontSize + 'px'
              }"
            >
              {{ item.type === 'el-text' ? item.props.content : '' }}
            </component>
            <div class="component-actions" v-show="selectedIndex === index">
              <el-button-group>
                <el-button size="small" @click="moveComponent(index, -1)">上移</el-button>
                <el-button size="small" @click="moveComponent(index, 1)">下移</el-button>
                <el-button size="small" type="danger" @click="deleteComponent(index)">删除</el-button>
              </el-button-group>
            </div>
          </div>
        </div>
      </el-main>
      
      <el-aside width="300px" class="props-panel">
        <div class="panel-title">属性配置</div>
        <template v-if="selectedIndex !== -1">
          <el-form label-position="top">
            <el-form-item 
              v-for="(prop, key) in getSelectedComponentProps"
              :key="key"
              :label="prop.label"
            >
              <el-input 
                v-if="prop.type === 'string'"
                v-model="page.config.components[selectedIndex].props[key]"
              />
              <el-input-number
                v-else-if="prop.type === 'number'"
                v-model="page.config.components[selectedIndex].props[key]"
              />
              <el-select
                v-else-if="prop.type === 'select'"
                v-model="page.config.components[selectedIndex].props[key]"
              >
                <el-option
                  v-for="opt in prop.options"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                />
              </el-select>
              <el-color-picker
                v-else-if="prop.type === 'color'"
                v-model="page.config.components[selectedIndex].props[key]"
              />
            </el-form-item>
          </el-form>
        </template>
      </el-aside>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { Picture, Document, Edit } from '@element-plus/icons-vue'
import { pageApi } from '@/api/page'

const router = useRouter()
const route = useRoute()

// 页面数据
const page = ref({
  title: '',
  config: {
    components: []
  }
})

// 组件库定义
const components = {
  'el-text': {
    type: 'el-text',
    label: '文本',
    icon: Document,
    props: {
      content: { 
        type: 'string', 
        label: '文本内容', 
        default: '文本内容' 
      },
      color: { 
        type: 'color', 
        label: '文字颜色', 
        default: '#333333' 
      },
      fontSize: { 
        type: 'number', 
        label: '字体大小', 
        default: 14 
      }
    }
  },
  'el-image': {
    type: 'el-image',
    label: '图片',
    icon: Picture,
    props: {
      src: { 
        type: 'string', 
        label: '图片地址',
        default: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'
      },
      fit: { 
        type: 'select', 
        label: '填充模式',
        options: [
          { label: '填充', value: 'fill' },
          { label: '包含', value: 'contain' },
          { label: '覆盖', value: 'cover' },
          { label: '不缩放', value: 'none' }
        ],
        default: 'cover'
      }
    }
  }
}

// 选中的组件索引
const selectedIndex = ref(-1)

// 获取选中组件的属性配置
const getSelectedComponentProps = computed(() => {
  if (selectedIndex.value === -1) return {}
  const component = page.value.config.components[selectedIndex.value]
  return components[component.type].props
})

// 拖拽开始
const handleDragStart = (e, componentType) => {
  e.dataTransfer.setData('componentType', componentType)
}

// 拖拽放置
const handleDrop = (e) => {
  const componentType = e.dataTransfer.getData('componentType')
  const componentConfig = components[componentType]
  
  // 创建新组件，并设置默认属性
  const newComponent = {
    type: componentType,
    props: {}
  }
  
  // 设置默认属性值
  Object.entries(componentConfig.props).forEach(([key, prop]) => {
    newComponent.props[key] = prop.default
  })
  
  page.value.config.components.push(newComponent)
  selectedIndex.value = page.value.config.components.length - 1
}

// 点击画布
const handleCanvasClick = () => {
  selectedIndex.value = -1
}

// 选中组件
const handleSelectComponent = (index) => {
  selectedIndex.value = index
}

// 移动组件
const moveComponent = (index, direction) => {
  const newIndex = index + direction
  if (newIndex < 0 || newIndex >= page.value.config.components.length) return
  
  const components = page.value.config.components
  const temp = components[index]
  components[index] = components[newIndex]
  components[newIndex] = temp
  
  selectedIndex.value = newIndex
}

// 删除组件
const deleteComponent = (index) => {
  page.value.config.components.splice(index, 1)
  selectedIndex.value = -1
}

// 保存页面
const handleSave = async () => {
  if (!page.value.title) {
    ElMessage.warning('请输入页面标题')
    return
  }
  
  try {
    if (page.value.id) {
      // 更新已有页面
      await pageApi.update(page.value.id, page.value)
    } else {
      // 创建新页面
      const res = await pageApi.create(page.value)
      page.value.id = res.id
    }
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 预览页面
const handlePreview = () => {
  if (!page.value.id) {
    ElMessage.warning('请先保存页面')
    return
  }
  router.push({
    name: 'preview',
    params: { id: page.value.id }
  })
}

// 加载页面数据
const loadPage = async (id) => {
  try {
    const data = await pageApi.getById(id)
    // 确保config是对的
    if (typeof data.config === 'string') {
      data.config = JSON.parse(data.config)
    }
    page.value = data
  } catch (error) {
    console.error('加载页面失败:', error)
    ElMessage.error('加载页面失败')
  }
}

onMounted(() => {
  const { id } = route.params
  if (id) {
    loadPage(id)
  }
})
</script>

<style lang="scss" scoped>
.editor-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .editor-header {
    padding: 12px;
    border-bottom: 1px solid #dcdfe6;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .editor-main {
    flex: 1;
    overflow: hidden;
    
    .components-panel {
      border-right: 1px solid #dcdfe6;
      background: #fff;
      
      .component-item {
        padding: 12px;
        display: flex;
        align-items: center;
        cursor: move;
        
        &:hover {
          background-color: #f5f7fa;
        }
        
        .el-icon {
          margin-right: 8px;
        }
      }
    }
    
    .canvas-container {
      background-color: #f5f7fa;
      padding: 20px;
      overflow-y: auto;
      
      .canvas {
        background-color: #fff;
        min-height: 100%;
        padding: 20px;
        
        .component-wrapper {
          position: relative;
          padding: 8px;
          margin: 4px 0;
          border: 1px dashed transparent;
          
          &:hover {
            border-color: #409eff;
          }
          
          &.active {
            border-color: #409eff;
            background-color: rgba(64, 158, 255, 0.1);
          }
          
          .component-actions {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
          }
        }
      }
    }
    
    .props-panel {
      border-left: 1px solid #dcdfe6;
      padding: 12px;
      background: #fff;
      overflow-y: auto;
      
      .el-form-item {
        margin-bottom: 18px;
      }
    }
  }
  
  .panel-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 12px;
    padding: 12px;
  }
}
</style> 